const morgan = require('morgan');
const FileStreamRotator = require('file-stream-rotator')
const path = require('path');
const fs = require('fs');

morgan.token('body', (req, res) => {
    return JSON.stringify(req.body);
})
morgan.token('x-access-token', (req, res) => {
    return req.headers['x-access-token'];
})
morgan.token('cookies', (req, res) => {
    return JSON.stringify(req.cookies);
})
morgan.token('type', (req, res) => {
    let type = 'INFO', statusCode = res.statusCode;
    if(statusCode >= 400 && statusCode < 500) type = 'WARNING';
    if(statusCode == 500) type = 'ERROR';
    return type;
})
morgan.format('LOGS', '[:type]  :remote-addr :method :url :status HTTP/:http-version :res[content-length]Bytes - :response-time ms ' +
                       'token::x-access-token Cookies::cookies Body::body'+
                       ' [:date[web]] :user-agent :referrer');


module.exports = app => {
    if(process.env.NODE_ENV === 'production') {
        let logDirectory = path.join(__dirname, '../../log/client');
        // ensure log directory exists
        fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
        // create a rotating write stream
        let accessLogStream = FileStreamRotator.getStream({
            date_format: 'YYYYMMDD',
            filename: path.join(logDirectory, 'access-%DATE%.log'),
            frequency: 'daily',
            verbose: false
        })
        app.use(morgan('LOGS', {stream: accessLogStream}));
    }else{
        app.use(morgan('LOGS'));
    }
}
